package com.zhongxi.guoyuan.widget.redpacket;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.SoundPool;
import android.media.SoundPool.OnLoadCompleteListener;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.utils.MyTextUtils;
import com.zhongxi.guoyuan.view.play.VideoActivity;
import com.zhongxi.guoyuan.view.play.RedPacketActivity;

import java.util.Random;

import pl.droidsonroids.gif.GifImageView;

public class LuckyDrawView extends RelativeLayout {

    protected static final String TAG = "LuckyDrawView";

    //摇出的金额
    private float money;

    private static final int PRIZE_COUNT = 9;

    private Handler mHandler = new Handler(getContext().getMainLooper());
    private LuckyDrawRunnable mLuckyDrawRunnable;

    /**
     * 开始按钮
     */
    private ImageView mStart;

    /**
     * 奖品Item
     */
    private LuckyDrawItem[] mLuckyDrawItem = new LuckyDrawItem[PRIZE_COUNT];
    private Vibrator vibrator;
    private Context context;
    private SoundPool soundPool;
    private boolean isPrepare = false;

    private int id;
    private String urlId;
    private String url;
    private boolean flag = false;

    public LuckyDrawView(Context context) {
        this(context, null);
    }

    public LuckyDrawView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    @SuppressWarnings("deprecation")
    public LuckyDrawView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        init();
        //初始化蜂鸣器
        vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        //初始化soundPool
        soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
        //加载声音到soundPool
        id = soundPool.load(context, R.raw.my, 0);
        //蜂鸣器准备完成的事件回调方法
        soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                isPrepare = true;
            }
        });

        // 属性
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.LuckyDrawView);
        Drawable startSrc = a.getDrawable(R.styleable.LuckyDrawView_startSrc);
        Drawable start_backgroud = a.getDrawable(R.styleable.LuckyDrawView_startBackgroud);
        Drawable prize_backgroud = a.getDrawable(R.styleable.LuckyDrawView_prizeBackgroud);
        a.recycle();

        mStart.setImageDrawable(startSrc);
        if (start_backgroud == null) {
            mStart.setImageResource(R.mipmap.bg_search);
        } else {
            mStart.setBackgroundDrawable(start_backgroud);
        }
        for (int i = 0; i < mLuckyDrawItem.length; i++) {
            if (prize_backgroud == null) {
                mLuckyDrawItem[i].setImageResource(R.drawable.lucky_draw_item_selector);
            } else {
                mLuckyDrawItem[i].setBackgroundDrawable(prize_backgroud);
            }
        }
    }

    public void onDestroyed() {
        soundPool.release();
    }

    private void init() {
        RelativeLayout.inflate(getContext(), R.layout.layout_lucky_draw_view, this);

        mLuckyDrawRunnable = new LuckyDrawRunnable(mHandler, mLuckyDrawItem, luckyDrawRotation());

        mStart = (ImageView) findViewById(R.id.v_lucky_draw_view_start);
        mStart.setOnClickListener(onClickStart());

        mLuckyDrawItem[0] = (LuckyDrawItem) findViewById(R.id.ld_lucky_draw_view_1);
        mLuckyDrawItem[1] = (LuckyDrawItem) findViewById(R.id.ld_lucky_draw_view_2);
        mLuckyDrawItem[2] = (LuckyDrawItem) findViewById(R.id.ld_lucky_draw_view_3);
        mLuckyDrawItem[3] = (LuckyDrawItem) findViewById(R.id.ld_lucky_draw_view_4);
        mLuckyDrawItem[4] = (LuckyDrawItem) findViewById(R.id.ld_lucky_draw_view_5);
        mLuckyDrawItem[5] = (LuckyDrawItem) findViewById(R.id.ld_lucky_draw_view_6);
        mLuckyDrawItem[6] = (LuckyDrawItem) findViewById(R.id.ld_lucky_draw_view_7);
        mLuckyDrawItem[7] = (LuckyDrawItem) findViewById(R.id.ld_lucky_draw_view_8);
        mLuckyDrawItem[8] = (LuckyDrawItem) findViewById(R.id.ld_lucky_draw_view_9);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    /**
     * 开始抽奖
     */
    public void start() {
        new Thread(mLuckyDrawRunnable).start();
        beginStop();
    }

    private void beginStop() {
        Random rd = new Random();
        int time = rd.nextInt(3000) + 2000;
        TimeCount timer = new TimeCount(time, 1000);
        timer.start();
    }

    public void setUrl(String url, String urlId, float money) {
        this.url = url;
        this.urlId = urlId;
        this.money = money;
        this.flag = true;
    }

    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {

        }

        @Override
        public void onFinish() {
            stop((int) (Math.random() * 7));
        }
    }

    /**
     * 停止抽奖并指定奖品
     *
     * @param end
     */
    public void stop(int end) {
        mLuckyDrawRunnable.stop(end);
    }

    /**
     *
     */
    public void clean() {
        for (int i = 0; i < mLuckyDrawItem.length; i++) {
            mLuckyDrawItem[i].setSelected(false);
        }
        mStart.setEnabled(false);
        setKeepScreenOn(false);
    }

    /**
     * 点击开始按钮
     *
     * @return
     */
    private OnClickListener onClickStart() {
        return new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (flag)
                    start();
            }
        };
    }

    /**
     * @return
     */
    private OnLuckyDrawRotationListener luckyDrawRotation() {
        return new OnLuckyDrawRotationListener() {
            @Override
            public void startRotation() {
                mStart.setEnabled(false);
                setKeepScreenOn(true);
                if (mOnLuckyDrawListener != null) {
                    mOnLuckyDrawListener.stop();
                }
            }

            @Override
            public void stopRotation() {
                mStart.setEnabled(true);
                setKeepScreenOn(false);
                if (mOnLuckyDrawListener != null) {
                    mOnLuckyDrawListener.start();
                }
            }
        };
    }


    /**
     * @param dp
     * @return
     */
    public int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getContext().getResources().getDisplayMetrics());
    }


    /**
     * @author Doots
     */
    private class LuckyDrawRunnable implements Runnable {

        private final int MIN_TIME_INTERVAL = 200;        // 最小时间间隔
        private final int MAX_TIME_INTERVAL = 500;        // 最大时间间隔

        /**
         * 时间间隔
         */
        private int mTimeInterval = 1000;

        /**
         * 停止位置
         */
        private int mEnd;

        /**
         * 高速旋转的圈数
         */
        private final int ROTATION_COUNT = 0;

        private Handler mMainHandelr;

        private OnLuckyDrawRotationListener mDrawStopListener;

        /**
         * 是否开始减速
         */
        private boolean isDeceleration;
        /**
         * 是否停止
         */
        private boolean isStop;

        /**
         * Items
         */
        private View[] mItems;


        public LuckyDrawRunnable(Handler handler, View[] items, OnLuckyDrawRotationListener l) {
            this.mMainHandelr = handler;
            this.mItems = items;
            this.mDrawStopListener = l;
            this.mTimeInterval = MAX_TIME_INTERVAL;
            this.isDeceleration = false;
        }

        @Override
        public void run() {
            start();
            stop();
        }

        /**
         * 开始旋转
         */
        private void start() {
            isStop = false;
            fristRotationPrize();
            while (!isStop) {
                rotationPrize();
            }
        }

        /**
         * 停止操作
         */
        private void stop() {
            for (int i = 0; i < ROTATION_COUNT; i++) {
                rotationPrize();
            }
            // 停止旋转
            isDeceleration = true;
            int count = 0;
            while (true) {
                nextPrize(mItems[count++ % mItems.length]);
                if (mTimeInterval >= (MAX_TIME_INTERVAL / 2)) {
                    break;
                }
            }
            lastRotationPrize(mEnd);
        }

        /**
         * 停止操作
         *
         * @param end
         */
        public void stop(int end) {
            isStop = true;
            mEnd = end;
        }

        /**
         * 刚开始首轮转动
         */
        private void fristRotationPrize() {
            if (mDrawStopListener != null) {
                mMainHandelr.post(new Runnable() {

                    @Override
                    public void run() {
                        mDrawStopListener.startRotation();
                    }
                });
            }
            int position = -1;
            for (int i = 0; i < mItems.length; i++) {
                if (mItems[i].isSelected()) {
                    position = i;
                    break;
                }
            }
            for (int i = (position == -1 ? 0 : position); i < mItems.length; i++) {
                nextPrize(mItems[i]);
            }
        }

        /**
         * 最后一轮转动，并转到指定的项上
         */
        private void lastRotationPrize(int end) {
            // 获取当前所在位置
            int position = 0;
            for (int i = 0; i < mItems.length; i++) {
                if (mItems[i].isSelected()) {
                    position = i;
                    break;
                }
            }
            if (position < end) {
                // 如果当前位置在停止位置后，则旋转到停止位置停止
                for (int i = ++position; i <= (end < mItems.length - 1 ? end : mItems.length - 1); i++) {
                    nextPrize(mItems[i]);
                }
            } else {
                // 如新当前位置在停止位置前，则先旋转到0,再继续旋转到停止位置停止
                for (int i = ++position; i < mItems.length; i++) {
                    nextPrize(mItems[i]);
                }
                for (int i = 0; i <= (end < mItems.length - 1 ? end : mItems.length - 1); i++) {
                    nextPrize(mItems[i]);
                }
            }
            if (mDrawStopListener != null) {
                mMainHandelr.post(new Runnable() {

                    @Override
                    public void run() {
                        clean();
                        mDrawStopListener.stopRotation();
                    }
                });
            }
            handler.sendEmptyMessage(0);
        }

        private Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                showPopupWindow();
            }
        };

        /**
         * 旋转
         */
        private void rotationPrize() {
            for (int i = 0; i < mItems.length; i++) {
                nextPrize(mItems[i]);
            }
        }

        private void nextPrize(final View v) {
            if (!isDeceleration) {
                mTimeInterval -= mTimeInterval / 8;
                if (mTimeInterval < MIN_TIME_INTERVAL) {
                    mTimeInterval = MIN_TIME_INTERVAL;
                }
            } else {
                mTimeInterval += mTimeInterval / 8;
                if (mTimeInterval > 2 * MAX_TIME_INTERVAL) {
                    mTimeInterval = 2 * MAX_TIME_INTERVAL;
                }
            }
            // 线程休眠，造成
            try {
                Thread.sleep(mTimeInterval);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 旋转到下一个item
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    cleanSelected();
                    v.setSelected(true);
                    if (isPrepare) {
                        soundPool.play(id, 1, 1, 0, 0, 1);
                    }
                }
            });
        }

        /**
         *
         */
        private void cleanSelected() {
            for (int i = 0; i < mItems.length; i++) {
                mItems[i].setSelected(false);
            }
        }

        private void clean() {
            isDeceleration = false;
            isStop = false;
            mTimeInterval = MAX_TIME_INTERVAL;
        }
    }

    private void showPopupWindow() {
        try {
            View contentView = LayoutInflater.from(context).inflate(R.layout.pop_red_packet, null);
            GifImageView gif = (GifImageView) contentView.findViewById(R.id.gif);
            gif.setBackgroundResource(R.mipmap.redpacket);
            TextView tvGet = (TextView) contentView.findViewById(R.id.tvGet);
            TextView tvCash = (TextView) contentView.findViewById(R.id.tvCash);
            tvCash.setText(MyTextUtils.tvStyle(context, "现金" + money + "元", 2, String.valueOf(money).length() + 2));
            final PopupWindow pw = new PopupWindow(contentView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
            //领取红包
            tvGet.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    pw.dismiss();
                    showVideoPopupWindow();
                }
            });
            pw.setTouchable(true);
            pw.setFocusable(true);
            backgroundAlpha(0.3f);
            pw.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    backgroundAlpha(1f);
                }
            });
            pw.showAtLocation(mStart, Gravity.CENTER, 0, 0);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void showVideoPopupWindow() {
        Intent intent = new Intent(context, VideoActivity.class);
        intent.putExtra("videoUrl", url);
        intent.putExtra("videoId", urlId);
        intent.putExtra("money", money + "");
        ((RedPacketActivity) context).startActivityForResult(intent, 500);
    }

    private void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = ((Activity) context).getWindow().getAttributes();
        lp.alpha = bgAlpha;
        ((Activity) context).getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        ((Activity) context).getWindow().setAttributes(lp);
    }

    private OnLuckyDrawListener mOnLuckyDrawListener;

    public void setOnLuckyDrawListener(OnLuckyDrawListener listener) {
        mOnLuckyDrawListener = listener;
    }

    /**
     * @author Doots
     */
    public interface OnLuckyDrawListener {
        public void start();

        public void stop();
    }

    /**
     * @author Doots
     */
    private interface OnLuckyDrawRotationListener {
        public void startRotation();

        public void stopRotation();
    }
}
